<!--
 * @Author: your name
 * @Date: 2021-04-12 13:00:43
 * @LastEditTime: 2022-03-04 11:54:22
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \cang-chu-guan-li-xi-tong\src\views\tuiKuGuanLi\saleOutCancelApple.vue
-->
<template>
  <a-card>
    <p style="font-size: 18px; text-align: center">销售出库退库</p>
    <br />
    <!-- 顶部的信息  -->
    <a-form-model ref="ruleForm" :model="Form" v-bind="layout" :rules="rules">
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号" prop="document" ref="document">
            <a-input
              style="border: 0"
              v-model="Form.document"
              disabled
            ></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="仓库名称"
            ref="applicationDepot_dictText"
            prop="applicationDepot_dictText"
          >
            <a-select
              v-model="Form.applicationDepot_dictText"
              showSearch
              style="width: 100%"
              @change="formDepotNameSelectChange"
            >
              <!-- @change="
                  (val) => {
                    const arr = val.split('|');
                    this.form.applicationDepot_dictText = arr[2];
                    this.form.depotId = arr[0];
                  }
                " -->
              <a-select-option
                v-for="item in storageList"
                :key="item.depotId"
                :value="
                  item.depotId +
                  '|' +
                  item.depotNo +
                  '|' +
                  item.applicationDepot_dictText
                "
                >{{ item.depotNo }}
                {{ item.applicationDepot_dictText }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="申请部门"
            ref="deptId_dictText"
            prop="deptId_dictText"
          >
            <a-tree-select
              v-model="Form.deptId_dictText"
              show-search
              style="width: 100%"
              :tree-data="depTree"
              allow-clear
              @change="changeTreeNode"
            ></a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="客户"
            ref="clientId_dictText"
            prop="clientId_dictText"
          >
            <a-select
              showSearch
              v-model="Form.clientId_dictText"
              @change="getfarmerId"
              @search="getAllfarmerList"
            >
              <a-select-option
                v-for="item in customerlist"
                :key="item.id"
                :value="item.No + '|' + item.name + '|' + item.id"
              >
                {{ item.No }} {{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="库存组织"
            ref="pkCalbody_dictText"
            prop="pkCalbody_dictText"
          >
            <a-select
              v-model="Form.pkCalbody_dictText"
              @change="getpk_calbodyId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in InventoryOrganizationList"
                :key="item.id"
                :value="item.pkCalbody + '|' + item.bodyname"
              >
                {{ item.bodyname }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="业务流程"
            ref="cbiztype_dictText"
            prop="cbiztype_dictText"
          >
            <a-select
              v-model="Form.cbiztype_dictText"
              style="width: 100%"
              placeholder="请选择业务流程"
              @change="handleBusinessProcess"
              showSearch
            >
              <a-select-option
                v-for="(item, index) in businessProcessList"
                :key="index"
                :value="item.businame + '|' + item.pkBusitype"
              >
                {{ item.businame }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="库管员"
            ref="cwhsmanagerid_dictText"
            prop="cwhsmanagerid_dictText"
          >
            <a-select
              @change="getcwhsmanager"
              v-model="Form.cwhsmanagerid_dictText"
              showSearch
              style="width: 100%"
              @search="searchUserInfoList"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName + '|' + item.userId"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="收发类别"
            ref="sendReceiveType_dictText"
            prop="sendReceiveType_dictText"
          >
            <a-select
              placeholder=""
              v-model="Form.sendReceiveType_dictText"
              @change="shoufaleibieMethod"
              showSearch
            >
              <a-select-option
                v-for="(item, index) in shoufaleibieList"
                :key="index"
                :value="item.id + '|' + item.name"
                >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="单据日期"
            prop="document_date"
            ref="document_date"
          >
            <a-date-picker
              v-model="Form.document_date"
              type="date"
              placeholder="请选择时间"
              @change="
                (a, b) => {
                  this.Form.a = a;
                  this.Form.document_date = b;
                  this.Form.balance = b;
                }
              "
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>

      <!-- 根据源单生成  -->

      <!-- 生成原单按钮组件 -->
      <saleOutCancelAppleOrigin
        v-if="!updateTag"
        @select-data="setGoodsListInfoByOrigin"
        @select-data2="setGoodsListInfoByOrigin2"
      ></saleOutCancelAppleOrigin>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        style="margin-top: 10px"
        :scroll="{ x: 2000 }"
        :pagination="false"
      >
        <!-- 仓库名称 -->
        <span slot="unitPrice" slot-scope="text, record">
          <a-input-number v-model="record.depotId" />
        </span>
        <!-- 存货名称 -->
        <span slot="inventoryName" slot-scope="text, record">
          <a-select
            v-model="record.inventoryName"
            style="width: 100%"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @search="handleSearch"
            @change="getInventoryInfo(record)"
            showSearch
          >
            <a-select-option
              v-for="(item, index) in goodsList"
              :key="index"
              :value="
                item.inventoryId +
                '|' +
                item.invcode +
                '|' +
                item.inventoryName +
                '|' +
                item.invspec +
                '|' +
                item.measname
              "
            >
              {{ item.invcode }} {{ item.inventoryName }}{{ item.invspec }}
            </a-select-option>
          </a-select>
        </span>
        <!-- 辅助单位 -->
        <span slot="auxiliaryUnit" slot-scope="text, record">
          <a-select
            v-model="record.auxiliaryUnit"
            style="width: 100%"
            @change="disableUnit(record.key)"
            showSearch
          >
            <a-select-option
              v-for="item in Auxiliary_Unitlist"
              :key="item.value"
              :value="item.title + '|' + item.value"
            >
              {{ item.value }} {{ item.title }}
            </a-select-option>
          </a-select>
        </span>
        <!-- 数量 -->
        <span slot="quantity" slot-scope="text, record">
          <a-input-number v-model="record.quantity" :step="0.001" />
        </span>
        <!-- 单价-->
        <span slot="unitPrice" slot-scope="text, record">
          <a-input-number v-model="record.unitPrice" />
        </span>
        <!-- 金额-->
        <span slot="money" slot-scope="text, record">
          <a-input-number v-model="record.money" />
        </span>
        <!-- 备注 -->
        <span slot="remark" slot-scope="text, record">
          <a-input v-model="record.remark" />
        </span>

        <template slot="action" slot-scope="text, record">
          <span v-if="record.isNew">
            <a @click="cancle(record.key)">取消</a>
          </span>
        </template>
      </a-table>
      <a-button
        style="width: 100%; margin-top: 16px; margin-bottom: 8px"
        type="dashed"
        icon="plus"
        @click="newMember"
        >添加</a-button
      >

      <a-row style="margin-top: 20px">
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="审核人" ref="inspector" prop="inspector">
            <a-select
              v-model="Form.inspector"
              showSearch
              @change="getInspectorId"
              style="width: 100%"
            >
              <a-select-option
                v-for="item in inspectorList"
                :key="item.userId"
                :value="item.userId + '|' + item.workNo + '|' + item.userName"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="审核日期">
            <a-date-picker
              v-model="Form.balance"
              type="date"
              style="width: 100%"
              disabled
            />
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="制单人">
            <a-input disabled v-model="Form.singleProducerName"> </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row>
        <center>
          <a-button
            @click="submit"
            :disabled="isAntiAudit"
            style="margin-right: 20px"
          >
            保存
          </a-button>
          <a-button
            @click="Auditfunction"
            style="margin-right: 20px"
            :disabled="!isAntiAudit"
          >
            审核
          </a-button>
        </center>
      </a-row>
    </a-form-model>
  </a-card>
</template>
<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
import moment from "moment";

import saleOutCancelAppleOrigin from "./saleOutCancelOrigin.vue"; //

// 规则
const rules = {
  document: [
    {
      required: true,
      message: "单据号不能为空！",
      trigger: "change",
    },
  ],

  applicationDepot_dictText: [
    {
      required: true,
      message: "仓库名称不能为空！",
      trigger: "change",
    },
  ],

  deptId_dictText: [
    {
      required: true,
      message: "申请部门不能为空！",
      trigger: "change",
    },
  ],

  // warehouseName: [
  //   {
  //     required: true,
  //     message: "所属仓库不能为空！",
  //     trigger: "change",
  //   },
  // ],
  clientId_dictText: [
    {
      required: true,
      message: "客户不能为空",
      trigger: "change",
    },
  ],
  sendReceiveType_dictText: [
    {
      required: true,
      message: "收发类别不能为空！",
      trigger: "change",
    },
  ],

  inspector: [
    {
      required: true,
      message: "审核人不能为空！",
      trigger: "change",
    },
  ],
  // 仓位
  position: [
    {
      required: true,
      message: "仓位不能为空！",
      trigger: "change",
    },
  ],

  // 库管员
  cwhsmanagerid_dictText: [
    {
      required: true,
      message: "库管员不能为空！",
      trigger: "change",
    },
  ],

  // 业务流程
  cbiztype_dictText: [
    {
      required: true,
      message: "业务流程不能为空！",
      trigger: "change",
    },
  ],
  // 库存组织
  pkCalbody_dictText: [
    {
      required: true,
      message: "库存组织不能为空！",
      trigger: "change",
    },
  ],
  // 公司
  pk_corp: [
    {
      required: true,
      message: "公司不能为空！",
      trigger: "change",
    },
  ],
  document_date: [
    {
      required: true,
      message: "单据日期不能为空！",
      trigger: "change",
    },
  ],
};

// 列表
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },
  // {
  //   title: "仓位",
  //   dataIndex: "position",
  //   key: "position",
  //   align: "center",
  // },
  /* {
    title: "仓库名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    align: "center",
    width: 300,
    scopedSlots: { customRender: "inventoryName" },
  }, */
  {
    title: "存货名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    align: "center",
    width: 300,
    scopedSlots: { customRender: "inventoryName" },
  },
  {
    title: "存货编码",
    dataIndex: "invcode",
    key: "invcode",
    align: "center",
    scopedSlots: { customRender: "invcode" },
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
  },
  {
    title: "单位",
    dataIndex: "measname",
    key: "measname",
    align: "center",
  },
  {
    title: "辅助单位",
    key: "auxiliaryUnit",
    dataIndex: "auxiliaryUnit",
    align: "center",
    width: 150,
    scopedSlots: { customRender: "auxiliaryUnit" },
  },
  {
    title: "数量",
    key: "quantity",
    dataIndex: "quantity",
    align: "center",
    scopedSlots: { customRender: "quantity" },
  },
  {
    title: "单价",
    key: "unitPrice",
    dataIndex: "unitPrice",
    align: "center",
    scopedSlots: { customRender: "unitPrice" },
  },
  {
    title: "金额",
    key: "money",
    dataIndex: "money",
    align: "center",
    scopedSlots: { customRender: "money" },
  },
  {
    title: "源单单号",
    key: "sourceNumber",
    dataIndex: "sourceNumber",
    align: "center",
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
    scopedSlots: { customRender: "remark" },
  },
  // {
  //   title: "操作",
  //   dataIndex: "action",
  //   key: "action",
  //   align: "center",
  //   fixed: "right",
  //   scopedSlots: { customRender: "action" },
  // },
];

export default {
  components: {
    saleOutCancelAppleOrigin,
  },
  data() {
    return {
      shoufaleibieList: [], //收发类别列表

      workNoList: [], // 判重使用
      UserList: [], // 库管员列表
      InventoryOrganizationList: [], // 库存组织列表
      businessProcessList: [], //业务流程列表

      customerlist: [], //客户列表

      goodsList: [],
      Form: {},
      empty_: true,
      storageList: [], // 仓库列表
      depTree: [], // 部门列表
      clientList: [], // 客户
      SyncBusinessTypeVoList: [], // 业务流程列表
      warehouseOrganizationList: [], // 库存组织列表
      inspectorList: [], // 审核人
      inventoryList: [], // 存货列表
      Auxiliary_Unitlist: [], // 辅助单位

      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      rules,
      columns,
      dataSource: [],
      isAntiAudit: false,
      updateTag: false,
    };
  },

  watch: {
    $route: function (to) {
      if (to.path == "/saleOutCancel") {
        this.initInfoMount();
      }
    },
  },
  mounted() {
    this.shoufaleibieListmethod(); //收发类别列表
    this.getBusinessTypeInfo(); //获取业务流程
    this.getApplyStorage(); // 获取仓库
    this.getDeparmentTree(); //获取部门树
    this.judgeDocument(); //判断单据号是否为空
    this.initInfoMount();
    this.getSyncInventoryOrganizationList(); //获取库存组织
    this.getInspectorList(); // 仓库审核人员
  },
  methods: {
    async handleSearch(value) {
      var goodsList_invname = [];
      var goodsList_invspec = [];
      if (value.match(/^[ ]*$/)) {
        console.log("字符串为空或全空格");
      } else {
        this.goodsList = [];
        console.log("value", value);
        let query = "?name=" + value;
        console.log("query", query);
        if (value == "" || value == null) {
          this.goodsList = [];
        } else {
          await comHttp
            .getgetSearchInventoryInformationFile(query)
            .then((res) => {
              console.log("结果为", res);
              // this.goodsList = res.result;
              for (let i = 0; i < res.result.length; i++) {
                if (
                  res.result[i].invspec == "null" ||
                  res.result[i].invspec == null
                ) {
                  res.result[i].invspec = "";
                }
                if (
                  res.result[i].measname == "null" ||
                  res.result[i].measname == null
                ) {
                  res.result[i].measname = "";
                }
                let data = {
                  inventoryId: res.result[i].pkInvbasdoc, // 存货 id
                  invcode: res.result[i].invcode, //存货编码
                  inventoryName: res.result[i].invname, //存货名称
                  invspec: res.result[i].invspec, //规格型号
                  measname: res.result[i].measname, //单位
                };
                goodsList_invname.push(data);
              }
            });
          let queryInventoryBySpec = "?invspec=" + value;
          //规格型号模糊查询
          await comHttp
            .getqueryInventoryBySpec(queryInventoryBySpec)
            .then((res) => {
              console.log("结果规格型号模糊查询", res);

              goodsList_invspec = res.result.list.map((item) => {
                return {
                  inventoryId: item.pkInvbasdoc,
                  invcode: item.invcode,
                  inventoryName: item.invname,
                  invspec: item.invspec,
                  measname: item.measname,
                };
              });
            });
          //todo 合并去重函数
          await this.mergeArray(goodsList_invname, goodsList_invspec);
        }
      }
    },
    //todo 合并去重函数
    mergeArray(arr1, arr2) {
      let arrs = [...arr1, ...arr2];

      //根据inventoryId去重
      let map = new Map();
      for (let item of arrs) {
        if (!map.has(item.inventoryId)) {
          map.set(item.inventoryId, item);
        }
      }
      this.goodsList = [...map.values()];
    },
    // 获取存货信息
    async getInventoryInfo(record) {
      console.log("record11111111111111111111111111", record);
      let key = record.key;
      let target = this.dataSource.filter((item) => item.key === key)[0];
      console.log("target", target);
      // 分割字符串,取出来存货编码
      let array = target.inventoryName.split("|");
      console.log("array", array);
      target.inventoryId = array[0];
      target.invcode = array[1]; // 赋值给存货编码
      target.inventoryName = array[2]; // 赋值给存货名称

      if (array[3] != "null") {
        target.invspec = array[3]; // 赋值给规格型号
      } else {
        target.invspec = "";
      }

      if (array[4] != "null") {
        target.measname = array[4]; // 赋值给单位
      } else {
        target.measname = ""; // 赋值给单位
      }

      // console.log("目标物品信息:::::",target.goodsList)

      // 递归查询出来物品信息
      // let goodsInfomation = [];
      // for (let i = 0; i < this.goodsList.length; i++) {
      //   if (this.goodsList[i].inventoryNo == array[0]) {
      //     goodsInfomation = this.goodsList[i];
      //   }
      // }
      // console.log("物品信息::::", goodsInfomation);
      // target.standardModel = goodsInfomation.standardModel;
      // target.unit = goodsInfomation.unit;
      target.auxiliaryUnit = ""; // 重置辅助单位
      target.auxiliaryUnitId = ""; // 重置辅助单位
      target.giveawayId = 2; //

      // target.BatchList = await this.getBatchNumberList(
      //   target.depotId,
      //   goodsInfomation.inventoryId
      // ); // 获取批次列表
      /*  console.log(" target.position", target.position);
      if (target.position == undefined || target.position == "undefined") {
        target.BatchList = await this.getBatchNumberList(
          target.depotId,
          target.inventoryId
        );
      } else {
        target.BatchList = await this.getBatchNumberList(
          target.depotId,
          target.inventoryId,
          target.position
        );
      } */

      // console.log("批次号列表::::", target.BatchList);
      console.log("批次号列表::::", target.BatchList);
      //获取现存总数量
      // target.balance = await this.getBalanceTemp(
      //   // target.depotId, //仓库Id
      //   // target.inventoryId //存货 id
      //   record
      // );
    },
    /* ——————————模糊查询结束—————————————— */

    //获取客户字典表
    getfarmerId(value, options) {
      console.log("供应商::::", value, options.key);
      let array = value.split("|");
      console.log("array", array);
      // this.form.supplier_dictText = array[1];
      // this.form.supplier = array[2];
      this.$set(this.Form, "clientId_dictText", array[1]);
      this.$set(this.Form, "clientId", array[2]);
    },
    getAllfarmerList(value) {
      if (value != "") {
        comHttp
          .queryByLikeName("?customerName=" + value + "&custflag=0,2")
          .then((res) => {
            this.customerlist = [];
            console.log("所有的客户信息::::", res);
            for (let i = 0; i < res.result.list.length; i++) {
              let data = {
                No: res.result.list[i].custcode, //编号
                id: res.result.list[i].pkCumandoc,
                name: res.result.list[i].custname,
              };

              this.customerlist.push(data);
            }
          });
        console.log("this.customerlist", this.customerlist);
      }
    },

    // 获取库存组织列表
    getSyncInventoryOrganizationList() {
      comHttp.getSyncInventoryOrganizationList().then((res) => {
        console.log("库存组织", res);
        this.InventoryOrganizationList = res.result;
      });
    },
    // 获取库存组织Id
    getpk_calbodyId(value) {
      console.log("value", value);
      let array = value.split("|");
      this.Form.pkCalbody = array[0];
      console.log("this.Form.pkCalbody", this.Form.pkCalbody);
    },
    // 仓库名称
    formDepotNameSelectChange(value) {
      let array = value.split("|");

      // 获取物品信息列表,根据仓库编码
      // let goodsList = this.getGoodSInfo(array[0]);
      this.Form.depotId = array[0];
      this.Form.applicationDepot_dictText = array[2];
      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.dataSource.length; i++) {
        this.dataSource[i].depotId = array[0];
        this.dataSource[i].depotNo = array[1];
        this.dataSource[i].applicationDepot_dictText = array[2];
        this.dataSource[i].batchNumber = this.todayBatchNumber;
        // ---                                      ---//
        // this.getGoodSInfo2(this.dataSource[i], array[0]);
        // this.getPositionListById(this.dataSource[i], array[0]); // 获取仓位信息
      }
      console.log("仓库获取:::::", this.dataSource);
    },

    getApplyStorage() {
      this.storageList = [];
      comHttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            applicationDepot_dictText: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },

    // 部门下拉框选择
    changeTreeNode(a) {
      console.log("a", a);
      let array = a.split("|");

      this.Form.deptId = array[0];
      this.Form.applicationDept = array[1];
      this.Form.deptId_dictText = array[1];
    },

    // 获取部门列表
    getDeparmentTree() {
      console.log("获取部门列表hanshu===");
      comHttp.getDepartmentList().then((res) => {
        if (res.success) {
          console.log("获取部门树", res);
          this.depTree = res.result;
          console.log(this.depTree, "111111111111111111");
          this.changeCorpData(this.depTree);
        }
      });
    },

    //业务流程
    handleBusinessProcess(value) {
      let arr = value.split("|");
      this.Form.cbiztype_dictText = arr[0];
      this.Form.cbiztype = arr[1];
    },
    // 业务流程
    getBusinessTypeInfo() {
      comHttp.getBusinessTypeInfo().then((res) => {
        console.log("获取业务流程字典表", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            pkBusitype: res.result[i].pkBusitype,
            businame: res.result[i].businame,
            busicode: res.result[i].busicode,
          };
          if (data.busicode.indexOf("0") == 0) {
            this.businessProcessList.push(data);
          }
        }
      });
    },

    // 改变用友传递过来的数据为组件能识别的数据
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.deptcode + " " + element.deptname;
        element["value"] = element.pkDeptdoc + "|" + element.deptname;
        element["children"] = element.syncDepartmentFilesEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.changeCorpData(element.children);
        }
        // element["title"] = element.deptname;
        // element["children"] = element.syncDepartmentFilesEntityList;
        // element["key"] = element.pkDeptdoc;
        // element["value"] = element.pkDeptdoc;

        // if (element.children) {
        //   this.changeCorpData(element.children);
        // }
      });
    },
    // ————判断单据号是否为空————
    judgeDocument() {
      setTimeout(() => {
        if (this.Form.document === "") {
          this.$message.error("未获取到单据号,请刷新页面重试");
        }
      }, 3000);
    },
    /* ------------------------------- 其他,表头和表尾 ----------------------------- */
    // 申请单号
    getApplyOrder() {
      let queryPath = "?string=XSCKT-";
      comHttp.getOrder(queryPath).then((res) => {
        this.Form.document = res.message;
      });
    },
    // 审核人
    getInspectorList() {
      const roleName = "仓库审核人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.inspectorList.push(data);
        }
      });
    },
    // 获取审核人Id
    getInspectorId(value, options) {
      this.Form.inspectorId = options.key;
    },
    // 库管员change函数
    getcwhsmanager(data) {
      console.log("data", data);
      let array = data.split("|");
      this.Form.cwhsmanagerid = array[2];
      this.Form.cwhsmanagerid_dictText = array[1];
    },
    // 查询人员信息列表
    searchUserInfoList(value) {
      // this.UserList = [];
      if (value != "") {
        let queryPath = "?username=" + value;
        console.log("queryPath", this.queryPath);
        comHttp.getUserInfoByUserName(queryPath).then((res) => {
          for (let i = 0; i < res.result.list.length; i++) {
            if (!this.workNoList.includes(res.result.list[i].workNo)) {
              let data = {
                userName: res.result.list[i].username,
                userId: res.result.list[i].id,
                workNo: res.result.list[i].workNo,
              };
              this.UserList.push(data);
              this.workNoList.push(res.result.list[i].workNo);
            }
          }
        });
      }
    },
    //收发类别触发函数
    shoufaleibieMethod(value) {
      console.log("收发类别触发函数value", value);
      let array = value.split("|");
      console.log("array", array);
      // 表格自动填充所属单位
      this.Form.sendReceiveType = array[0]; //收发类别id
      this.Form.sendReceiveType_dictText = array[1]; //收发类别name
    },

    //收发类别列表
    shoufaleibieListmethod(queryPath = "") {
      console.log("hfougdiuy");
      comHttp.getReceiveSendTypeListAll(queryPath).then((res) => {
        console.log("收发类别列表", res);
        this.shoufaleibieList = res.result;
      });
    },

    /* -------------------------- 表格 ------------------------- */

    // 通过源单生成数据
    setGoodsListInfoByOrigin(data) {
      console.log("传递过来的数据:::::", data);

      // 销售订单Id
      this.Form.saleOrderAddId = data.saleOrderAddId;
      // 给表单赋值

      // 部门
      this.Form.deptId = data.deptId;
      this.Form.deptId_dictText = data.deptId_dictText;
      // 所属仓库
      // this.Form.depotId = data.goodsList.depotId;
      // this.Form.applicationDepot_dictText = data.goodsList.depotId_dictText;

      // 客户
      this.Form.clientId = data.clientId;
      this.Form.clientId_dictText = data.clientId_dictText;
      // 业务类型
      this.Form.cbiztype = data.cbiztype;
      this.Form.cbiztype_dictText = data.cbiztype_dictText;

      // 库管员
      this.Form.cwhsmanagerid_dictText = data.cwhsmanagerid_dictText;
      this.Form.cwhsmanagerid = data.cwhsmanagerid;

      // 库存组织
      this.Form.pkCalbody = data.pkCalbody;
      this.Form.pkCalbody_dictText = data.pkCalbody_dictText;

      // 收发类别
      this.Form.sendReceiveType_dictText = data.sendReceiveType_dictText;
      this.Form.sendReceiveType = data.sendReceiveType;

      this.dataSource = data.goodsList; // 给列表赋值

      this.dataSource.forEach((element) => {
        element.remark = "";
      });
    },
    setGoodsListInfoByOrigin2(data) {
      console.log("传递过来的物品数据:::::", data);
      this.$set(this.Form, "depotId", data[0].supplierId);
      this.$set(
        this.Form,
        "applicationDepot_dictText",
        data[0].depotId_dictText
      );
      data.forEach((item) => {
        item.inventoryName = item.invname;
        // item.depotId = item.depotId;
      });
    },
    // 页面和路由跳转加载函数
    initInfoMount() {
      if (typeof this.$route.query.Id != "undefined") {
        console.log("--------- 更新视图 销售退库  ----------");
        this.routerJumpSetInitInfo(this.$route.query.Id);
      } else {
        this.initInfo();
      }
    },
    // 初始化加载信息
    initInfo() {
      this.updateTag = false;
      this.Form = {
        document: "", // 单据号
        document_date: moment().format("YYYY-MM-DD"),
        balance: moment().format("YYYY-MM-DD"),
        singleProducerName: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
      };
      this.dataSource = [];
      this.getApplyOrder();
    },

    // 路由跳转,设置初始化信息
    routerJumpSetInitInfo(id) {
      if (this.$route.query.isAntiAudit == "已反审核") {
        this.isAntiAudit = true;
      }
      this.updateTag = true;
      comHttp
        .getInOrOutStorageOrderAndGoodsInfoById("?id=" + id)
        .then((res) => {
          console.log(res);
          this.Form = {};
          this.dataSource = [];
          /* ------------- 设置表单信息 -------------- */
          this.Form.id = res.result.list[0].id;
          this.Form.document = res.result.list[0].document;
          this.$set(
            this.Form,
            "document_date",
            res.result.list[0].documentDate
          );
          this.Form.applicationDepot_dictText = res.result.list[0].storname; // 仓库名称
          // 部门
          this.Form.deptId_dictText = res.result.list[0].deptId_dictText;
          // 所属仓库

          // 客户
          this.Form.clientId_dictText = res.result.list[0].clientId_dictText;
          // 业务类型
          this.Form.cbiztype_dictText = res.result.list[0].cbiztype_dictText;

          // 库管员
          this.Form.cwhsmanagerid_dictText =
            res.result.list[0].cwhsmanagerid_dictText;

          // 库存组织
          this.Form.pkCalbody_dictText = res.result.list[0].pkCalbody_dictText;

          // 收发类别
          this.Form.sendReceiveType_dictText =
            res.result.list[0].sendReceiveType_dictText;
          this.Form.balance = res.result.list[0].balance; //审核日期

          // 审核人
          this.$set(this.Form, "inspectorId", res.result.list[0].inspector);
          this.$set(
            this.Form,
            "inspector",
            res.result.list[0].inspector_dictText
          );

          // 制单人
          this.Form.singleProducerName =
            res.result.list[0].singleProducer_dictText;

          let i = 0;
          res.result.list.forEach((element) => {
            let data = {
              id: element.twoId,
              key: i + 1,
              inventoryName: element.invname,
              depotId: element.depotId,
              invcode: element.invcode,
              invspec: element.invspec,
              measname: element.measname,
              auxiliaryUnit: element.auxiliaryUnit_dictText,
              sourceNumber: element.sourceNumber,
              remark: element.remark,
              quantity: element.quantity,
            };
            i = i + 1;
            this.dataSource.push(data);
          });
        });
    },
    //  校验是否为空
    checkempty(submitData) {
      this.empty_ = true;
      console.log("11111", submitData);
      var message = []; //提示信息
      /*  if (this._xxx.length === 0) {
        this.empty_ = false;
        message.push("请添加列表信息!" + "\xa0\xa0\xa0");
      } */
      /* if (this.DataSource.element.length ===0) {
        this.empty_ = false;
        message.push("请添加列表信息!" + "\xa0\xa0\xa0");
      } */
      this.dataSource.forEach((element) => {
        console.log("element", element);
        if (!element.depotId) {
          this.empty_ = false;
          message.push("请再选择一次仓库!" + "\xa0\xa0\xa0");
        }
        if (!element.inventoryName) {
          this.empty_ = false;
          message.push("存货信息不能为空!" + "\xa0\xa0\xa0");
        }
        if (!element.quantity) {
          this.empty_ = false;
          message.push("存货数量不能为空!" + "\xa0\xa0\xa0");
        }
      });

      if (!this.empty_) {
        this.$message.error(message);
      }
    },
    // 新增提交
    addSubmit() {
      let array = [];
      console.log("提交的array", this.dataSource);
      console.log(this.dataSource.length);
      this.dataSource.forEach((element) => {
        let data = {
          inventoryId: element.inventoryId,
          auxiliaryUnit: element.auxiliaryUnit,
          quantity: element.quantity,
          sourceNumber: element.sourceNumber,
          remark: element.remark,
          depotId: element.depotId, // 仓库名称
          // storageUnit：this.Form.所属仓库
          objectInformationId: element.objectInformationId, //出入库物品ID
          saleSalesOrderRequestFormId: element.stockNotificationContentId, //根据源单（销售出库）生成的物品ID
        };
        array.push(data);
      });

      //  let  array
      let submitData = {
        auditMark: 2, // 未审核是 1 , 已审核是 2
        bookkeepingMark: 2,
        inOutCategoryIdentification: 8, // 销售退库
        inOutIdentification: 3, // 退库

        saleOrderAddId: this.Form.saleOrderAddId || "", // 销售订单Id
        document: this.Form.document, // 单据号
        cbiztype: this.Form.cbiztype, // 业务类型
        deptId: this.Form.deptId, // 部门
        clientId: this.Form.clientId, // 客户
        documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"), // 单据日期
        balance: moment(this.Form.balance).format("YYYY-MM-DD"), // 单据日期

        pkCalbody: this.Form.pkCalbody, // 库存组织

        cwhsmanagerid: this.Form.cwhsmanagerid, // 库管员
        sendReceiveType: this.Form.sendReceiveType, // 收发类别

        inspector: this.Form.inspectorId, // 审核人
        singleProducer: this.Form.singleProducerId, // 制单人
        warehouseObjectInformationEntities: array,
      };

      console.log("要提交的数据为:::::", submitData);

      if (this.dataSource.length != 0) {
        this.checkempty(submitData); //校验
        if (this.empty_ === true) {
          // 保存退库信息
          comHttp.addInOrOutStorageOrderAndGoods(submitData).then((res) => {
            if (res.success == true) {
              this.$message.success("保存成功");
              this.initInfo();
            } else {
              this.$message.error("保存失败");
            }
          });
        }
      } else {
        this.$message.error("请添加列表信息!");
      }
    },
    // 修改提交
    updateSubmit() {
      let array = [];
      this.dataSource.forEach((element) => {
        let data = {
          id: element.id,
          quantity: element.quantity,
          remark: element.remark,
        };
        array.push(data);
      });

      let submitForm = {
        id: this.Form.id,
        inspector: this.Form.inspectorId,
        documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"),
        balance: moment(this.Form.document_date).format("YYYY-MM-DD"),
        warehouseObjectInformationEntities: array,
      };

      // 修改全部的信息
      comHttp.updateInOrOutStorageOrderAndGoods(submitForm).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success("修改成功");
          setTimeout(
            this.$router.push({
              path: "/saleOutCancelList",
            }),
            1000
          );
        } else {
          this.$message.error("修改失败");
        }
      });
    },
    // 审核修改
    Auditfunction() {
      let array = [];
      this.dataSource.forEach((element) => {
        let data = {
          id: element.id,
          quantity: element.quantity,
          remark: element.remark,
        };
        array.push(data);
      });

      let submitForm = {
        id: this.Form.id,
        inspector: this.Form.inspectorId,
        // documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"),
        warehouseObjectInformationEntities: array,
      };

      // 修改信息
      comHttp.updateInOrOutStorageOrderAndGoods(submitForm).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success("审核成功");

          //标志位修改
          this.postSynchronized("未同步");
          this.update_audit("未反审核");
          this.update_Mark(1);
          this.$router.push("/saleOutCancelList");
        } else {
          this.$message.error("审核失败，请重新检查数据");
        }
      });
    },
    //! 是否同步标志位
    postSynchronized(isOrNo) {
      let data = {
        id: this.Form.id,
        isSynchronized: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //是否反审核标志位
    update_audit(isOrNo) {
      let data = {
        id: this.Form.id,
        isAntiAudit: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //审核标志位
    update_Mark(isOrNo) {
      let data = {
        id: this.Form.id,
        auditMark: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    // 提交
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          //  这是新增提交
          if (this.updateTag == false) {
            this.addSubmit();
          } else {
            // 这是修改提交
            this.updateSubmit();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 表格添加新的一条记录
    newMember() {
      console.log("增加一条记录");
      this.savebalance = Infinity;
      this.dataSource.push({
        key: this.dataSource.length + 1,
        isNew: true,

        depotNo: "", // 仓库编码、
        depotId: this.Form.depotId, //仓库id
        quantity: "", //数量
        unitPrice: "", //单价
        invcode: "", // 存货编码
        invname: "", //  存货名称
        inventoryName: "",
        // standardModel: "", //规格型号
        invspec: "", //规格型号
        measname: "", // 单位
        position: "", // 仓位
        sourceNumber: "", // 源单单号（外键）
        batchNumber: "", // 批次号
        giveaway: "2", // 是否赠品
        remark: "", // 备注
        goodsList: [], // 物品信息列

        storageDate: moment().format("YYYY-MM-DD"), //入库日期
      });
      console.log("this.dataSource", this.dataSource);
    },
  },
};
</script>